<template>
  <!-- examples\webgl_geometry_text_shapes.html -->
  <div ref="canvas"></div>
</template>

<script>
import * as THREE from 'three';
import { FontLoader } from 'three/examples/jsm/loaders/FontLoader.js';
import helvetikerBoldJSON from 'three/examples/fonts/helvetiker_bold.typeface.json';

export default {
  mounted() {
    const canvas = this.$refs.canvas;
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0xf0f0f0);

    const camera = new THREE.PerspectiveCamera(
      45,
      canvas.clientWidth / canvas.clientHeight,
      0.1,
      10000
    );
    camera.position.set(0, -400, 600);

    const loader = new FontLoader();
    // loader.load('/fonts/helvetiker_regular.typeface.json', function (font) {
    loader.load(helvetikerBoldJSON, function (font) {
      const color = 0x006699;

      const matDark = new THREE.LineBasicMaterial({
        color: color,
        side: THREE.DoubleSide,
      });

      const matLite = new THREE.MeshBasicMaterial({
        color: color,
        transparent: true,
        opacity: 0.4,
        side: THREE.DoubleSide,
      });

      const message = '   Three.js\nSimple text.';
      const shapes = font.generateShapes(message, 100);
      const geometry = new THREE.ShapeGeometry(shapes);
      geometry.computeBoundingBox();

      const xMid =
        -0.5 * (geometry.boundingBox.max.x - geometry.boundingBox.min.x);

      geometry.translate(xMid, 0, 0);

      const text = new THREE.Mesh(geometry, matLite);
      text.position.z = -150;
      scene.add(text);

      const holeShapes = [];
      for (let i = 0; i < shapes.length; i++) {
        const shape = shapes[i];

        if (shape.holes && shape.holes.length > 0) {
          for (let j = 0; j < shape.holes.length; j++) {
            const hole = shape.holes[j];
            holeShapes.push(hole);
          }
        }
      }

      shapes.push.apply(shapes, holeShapes);

      const lineText = new THREE.Object3D();

      for (let i = 0; i < shapes.length; i++) {
        const shape = shapes[i];

        const points = shape.getPoints();
        const geometry = new THREE.BufferGeometry().setFromPoints(points);

        geometry.translate(xMid, 0, 0);

        const lineMesh = new THREE.Line(geometry, matDark);
        lineText.add(lineMesh);
      }

      scene.add(lineText);

      render();
    });

    // 渲染场景
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setClearColor(0x262626);
    renderer.setSize(canvas.clientWidth, canvas.clientHeight);

    canvas.appendChild(renderer.domElement);

    function render() {
      renderer.render(scene, camera);
    }
  },
};
</script>

<style>
#canvas {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  z-index: -1;
}
</style>
